package club.itstudio.IContainer.container;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ContainerManager {

    private ExecContainerCommand execContainerCommand;

    // create and run a container
    public void Create(ContainerArgs args) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("run -d "); // daemon
        sb.append("--name ").append(args.getName()).append(' ');
        // resource limit
        if (!"".equals(args.getMemoryLimit())) {
            sb.append("-m ").append(args.getMemoryLimit()).append(' ');
        }
        if (!"".equals(args.getCpuShareLimit())) {
            sb.append("-cpushare ").append(args.getCpuShareLimit()).append(' ');
        }
        if (!"".equals(args.getCpuSetLimit())) {
            sb.append("-cpuset ").append(args.getCpuSetLimit()).append(' ');
        }

        // password
        sb.append("-e ").append("NEWPASS=").append(args.getNewPassword()).append(' ');
        // network
        sb.append("-net ").append(args.getNetworkName()).append(' ');
        // ssh port
        sb.append("-p ").append(args.getSshPort()).append(":").append("22").append(' ');
        // image
        sb.append(args.getImageName()).append(' ');
        // init command
        sb.append("bash .init.sh");

        execContainerCommand.Exec(sb.toString());
    }

    // stop the container
    public void Stop(String containerName) throws IOException {
        String command = "stop " + containerName;
        execContainerCommand.Exec(command);
    }

    // remove the container
    public void Remove(String containerName) throws IOException {
        String command = "rm " + containerName;
        execContainerCommand.Exec(command);
    }

    // commit the image
    public void commit(String containerName, String imageName) throws IOException {
        String command = "commit " + containerName + " " + imageName;
        execContainerCommand.Exec(command);
    }

    @Autowired
    public void setExecContainerCommand(ExecContainerCommand execContainerCommand) {
        this.execContainerCommand = execContainerCommand;
    }
}
